<template>
  <div id="tableContent">
    <cs-card class="cs-card_noFold" :class="{ 'cs-card_Fold': drawerBoxFold == true }">
      <el-table
        v-loading="isLoading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="selectionChange"
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column prop="companyName" label="企业名称" width="350"> </el-table-column>
        <el-table-column prop="siteName" label="站点" width="120"> </el-table-column>
        <el-table-column label="车牌号" width="100">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="right">
              <p>{{ scope.row.carNum }}</p>
              <div slot="reference" class="name-wrapper">
                {{ scope.row.carNum }}
              </div>
            </el-popover>
          </template>
          <!-- <template v-slot="scoped">
            <cs-tag>{{ scoped.row.carNum }}</cs-tag>
          </template> -->
        </el-table-column>
        <el-table-column prop="axleNum" label="总轴数" width="160"> </el-table-column>
        <el-table-column prop="totalWeight" label="总质量(KG)" width="120"> </el-table-column>
        <el-table-column prop="stdWeight" label="总质量限值(KG)" width="180"> </el-table-column>
        <el-table-column prop="overweightType" label="是否超重" width="120">
          <template v-slot="scoped">
            <cs-text :type="getTextType(scoped.row.overweightType)">{{
              getCSText(scoped.row.overweightType)
            }}</cs-text>
          </template>
        </el-table-column>
        <el-table-column prop="overRate" label="超重率(%)" width="140">
          <template v-slot="scoped">
            <cs-text :type="getTextType(scoped.row.overweightType)">
              <!-- 手动计算超重率 -->
              {{ toPercentage(scoped.row.overWeight / scoped.row.stdWeight).handleNum2 }}%
            </cs-text>
          </template>
        </el-table-column>
        <el-table-column label="检测时间" width="160">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="left">
              <p>{{ scope.row.createTime }}</p>
              <div slot="reference" class="name-wrapper">
                {{ scope.row.createTime }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template v-slot="scoped">
            <el-link v-if="innerMenu.que.flag" type="primary" @click="detailBtnClick(scoped.row.id)"
              >详情</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div id="pagination_section">
        <span class="currentSelect">{{ `共${totalCount}项` }}</span>
        <div class="pagination_right">
          <span>{{ `${pageSize}条/页` }}</span>
          <cs-pagination
            :currentPage="currentPage"
            :totalPage="totalPage"
            @firstPageClick="firstPageClick"
            @previousPageClick="previousPageClick"
            @nextPageClick="nextPageClick"
            @lastPageClick="lastPageClick"
            @junkToOtherPage="junkToOtherPage"
          />
        </div>
      </div>
    </cs-card>
  </div>
</template>

<script>
import csCard from '@/components/cs-card/cs-card.vue'
import csPagination from '@/components/cs-pagination/cs-pagination.vue'
// import csTag from '@/components/cs-tag/cs-tag.vue'
import csText from '@/components/cs-text/cs-text.vue'

import { getDataSearchTableData, earlyexport } from '@/service/monitor/early_warning/early_warning'
import { toPercentage } from '@/utils/dataConversion'
import { mapState } from 'vuex'

export default {
  components: {
    csCard,
    csPagination,
    // csTag,
    csText
  },
  props: {
    innerMenu: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      drawerBoxFold: true,
      // 当前页码
      currentPage: 1,
      // 一页的条数
      pageSize: 10,
      // 总共多少条数据
      totalCount: 0,
      // 总共多少页
      totalPage: 0,
      currentSelect: 0,
      selectId: [],
      tableData: [
        // {
        //   siteName: '测试',
        //   carNum: '桂E',
        //   carType: '电动车',
        //   axleNum: 2,
        //   totalWeight: 5,
        //   stdWeight: 6,
        //   overWeight: 7,
        //   overweightType: 1,
        //   overRate: 1,
        //   createTime: 2021
        // }
      ],
      isLoading: false
    }
  },
  created() {
    this.$bus.$on('drawerBoxStatusChange_earlyWarning', (status) => {
      this.drawerBoxFold = status
    })
    this.getDataSearchTableData()
    // 头部搜索按钮点击事件
    this.$bus.$on('earlyWarningSearchEvent', (data) => {
      if (this.isLoading) return
      console.log(data)
      const { carNumber, siteName, overweightTye, time } = data
      this.carNumber = carNumber
      this.siteName = siteName
      this.overweightTye = overweightTye
      this.startTime = time ? time[0] : ''
      this.endTime = time ? time[1] : ''
      this.getDataSearchTableData(1, 10)
    })
    // 当侧边栏更新时更新表格
    this.$bus.$on('earlyWarningDrawerDataUpdate', () => {
      this.getDataSearchTableData(this.currentPage, this.pageSize)
    })
    this.$bus.$on('earlyexportlist', (res) => {
      const obj = {
        carNumber: res.carNum,
        siteName: res.site,
        companyName: res.enterpriseName,
        overweightTye: res.isOverload,
        startTime: res.startTime,
        endTime: res.endTime
      }
      this.earlyexportfn(obj)
    })
    console.log(this.blackMsg)
  },
  beforeDestroy() {
    this.$bus.$off('earlyexportlist')
    this.$bus.$off('siteSelectNum')
    this.$bus.$off('earlyWarningDrawerId')
    this.$bus.$off('showDrawer')
    this.$bus.$off('drawerBoxStatusChange_earlyWarning')
  },
  computed: {
    ...mapState('m_msg', ['blackMsg'])
  },
  watch: {
    blackMsg(newValue) {
      if (newValue) {
        this.getDataSearchTableData(this.currentPage, this.pageSize)
      }
    }
  },
  methods: {
    toPercentage,
    // 表格选择项变化时触发事件
    selectionChange(selection) {
      this.selectId = []
      // 获取当前选择多少项
      this.currentSelect = selection.length
      this.$bus.$emit('siteSelectNum', this.currentSelect)
      selection.forEach((item) => {
        this.selectId.push(item.id)
      })
      console.log(this.selectId)
    },
    // 获取表格数据
    async getDataSearchTableData(
      pageNum = 1,
      pageSize = 10,
      carNumber = this.carNumber,
      siteName = this.siteName,
      overweightTye = this.overweightTye,
      startTime = this.startTime,
      endTime = this.endTime
    ) {
      this.isLoading = true
      try {
        const data = await getDataSearchTableData({
          pageNum,
          pageSize,
          carNumber,
          siteName,
          overweightTye,
          startTime,
          endTime
        })
        if (data.code === 0) {
          const tableData = data.data
          this.tableData = []
          this.totalCount = 0
          tableData.list.forEach((item) => {
            this.tableData.push({ ...item })
          })
          // 当前页码
          this.currentPage = tableData.currPage - 0
          // 一页的条数
          this.pageSize = tableData.pageSize
          this.totalCount = tableData.totalCount
          this.totalPage = tableData.totalPage - 0
          console.log(tableData)
          this.isLoading = false
        }
      } catch (err) {
        console.log(err)
        this.$message.error('获取表格数据失败')
      }
    },
    async earlyexportfn(obj) {
      const texts = '共' + this.totalCount + '条数据下载中'
      const loading = this.$loading({
        lock: true,
        text: texts,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const data = await earlyexport(obj)
      if (!!data) {
        const filename = '实时预警.xlsx'
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(filename))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(filename))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
        setTimeout(() => {
          loading.close()
        }, 2000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 2000)
      }
    },
    // 第一页
    firstPageClick() {
      if (this.isLoading) return
      this.getDataSearchTableData(1)
    },
    // 上一页
    previousPageClick() {
      if (this.isLoading) return
      this.getDataSearchTableData(this.currentPage - 1)
    },
    // 下一页
    nextPageClick() {
      if (this.isLoading) return
      this.getDataSearchTableData(this.currentPage + 1)
    },
    // 最后一页
    lastPageClick() {
      if (this.isLoading) return
      this.getDataSearchTableData(this.totalPage)
    },
    // 跳转页
    junkToOtherPage(page) {
      this.getDataSearchTableData(page, this.pageSize)
    },
    // 获取文字类型
    getTextType(type) {
      if (type === 0) {
        return 'success'
      } else if (type === 1) {
        return 'mildWarning'
      } else if (type === 2) {
        return 'warning'
      } else {
        return 'danger'
      }
    },
    getCSText(type) {
      if (type === 0) {
        return '没有超重'
      } else if (type === 1) {
        return '轻度超重'
      } else if (type === 2) {
        return '较轻超重'
      } else {
        return '严重超重'
      }
    },
    detailBtnClick(id) {
      console.log(id)
      this.$bus.$emit('earlyWarningDrawerId', id)
      this.$bus.$emit('showDrawer')
      this.drawerBoxFold = false
      console.log(this.drawerBoxFold)
    }
  }
}
</script>

<style scoped>
/* .cs-card >>> .el-card__body {
  padding-right: 30px;
} */

/* 侧边栏展开时cs-card的宽度 */
.cs-card_noFold {
  /* width: 100%; */
  width: calc(100% - 310px);
  /* width: 88%; */
  transition: width 0.3s ease;
}
/* 侧边栏折叠时cs-card的宽度 */
.cs-card_Fold {
  /* width: calc(100% + 356px); */
  width: 100%;
  transition: width 0.3s ease;
}

/* 表格样式start */
.el-form-item >>> .el-form-item__label {
  color: #888888;
}

.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-textarea >>> .el-textarea__inner {
  border-radius: 0;
}

.form-select {
  width: 100%;
}

.el-link {
  display: inline-block;
}

/* 表格选择框样式start */
.el-table >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.el-table >>> .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
}

.el-table >>> .el-checkbox__inner::before {
  top: 8px;
}
/* 表格选择框样式end */

/* 去掉switch外层的div溢出隐藏 */
.el-table >>> .cell {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 设置switch的宽高边框 */
.el-switch >>> .el-switch__core {
  width: 28px !important;
  height: 14px;
  border: 2px solid #dddddd !important;
}

/* 设置switch圆形按钮的宽高边框位置 */
.el-switch >>> .el-switch__core:after {
  top: -4px;
  width: 14px;
  height: 14px;
  border: 2px solid #dddddd;
}

/* 设置switch圆形按钮的激活位置 */
.el-switch.is-checked >>> .el-switch__core::after {
  left: 106%;
}

/* 设置switch圆形按钮的关闭位置 */
.el-switch >>> .el-switch__core:after {
  left: -2px;
}

/* 降低点击弹出侧边栏又收回去后出现在表格右下角的小横线 */
.el-table >>> .el-table__fixed-right::before {
  z-index: 1;
}

/* 表格样式end */
</style>
